<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getRuleListAPI, deleteRuleListAPI } from '@/api/carRule';
import { utils, writeFileXLSX } from 'xlsx';
import {Delete,Edit,Star} from '@element-plus/icons-vue'
import { addFeeRuleAPI, editRuleListAPI, showRuleListAPI } from '@/api/carRule';
const ruleList = ref([]);
const params = reactive({
  page: 1,
  pageSize: 5
});
const total = ref(0);
const dialogVisible = ref(false);
const addRuleRef = ref(null)
// 计费规则表单
const addForm = reactive({
    ruleNumber: '', // 计费规则编号
    ruleName: '', // 计费规则名称
    chargeType: 'duration', // 计费规则类型 duration / turn / partition
    chargeCeiling: null,
    freeDuration: null,
    // 时长计费独有字段
    durationTime: null, // 时长计费单位时间
    durationPrice: null, // 时长计费单位价格
    durationType: 'hour',
    // 按次收费独有字段
    turnPrice: null,
    // 分段计费独有字段
    partitionFrameTime: null, // 段内时间
    partitionFramePrice: null, // 段内费用
    partitionIncreaseTime: null, // 超出时间
    partitionIncreasePrice: null // 超出费为收费价钱
  });
  // 添加计费规则 规则
  const addFormRules = reactive({
    ruleNumber: [
      { required: true, message: '请输入规则编号', trigger: 'blur' }
    ],
    ruleName: [
      { required: true, message: '请输入规则名称', trigger: 'blur' }
    ],
    chargeType: [
      { required: true, message: '请选择收费类型', trigger: 'blur' }
    ],
    durationTime: [
      { required: true, message: '请输入时间', trigger: 'blur' }
    ],
    durationPrice: [
      { required: true, message: '请输入金额', trigger: 'blur' }
    ],
    turnPrice: [
      { required: true, message: '请输入每次的价格', trigger: 'blur' }
    ],
    partitionFrameTime: [
      { required: true, message: '请输入段内时长', trigger: 'blur' }
    ],
    partitionFramePrice: [
      { required: true, message: '请输入段内费用', trigger: 'blur' }
    ],
    partitionIncreaseTime: [
      { required: true, message: '请输入超出时间', trigger: 'blur' }
    ],
    partitionIncreasePrice: [
      { required: true, message: '请输入超出金额', trigger: 'blur' }
    ]
  });
  // 编辑的id
  const editId = ref(0);

onMounted(() => {
  getRuleList();
});
// 获取计费规则列表
const getRuleList = async () => {
  const res = await getRuleListAPI(params);
  ruleList.value = res.data.rows;
  total.value = res.data.total;
};
// 切换页面
const editPageList = (currentPage) => {
  params.page = currentPage;
  getRuleList();
};
// 页面编号显示
const indexMethod = (index) => {
  return (params.page - 1) * params.pageSize + index + 1;
};
// 导出数据
const exportExcel = async () => {
  const res = await getRuleListAPI(params);
  const tableHeaderKeys = ['ruleNumber', 'ruleName', 'freeDuration', 'chargeCeiling', 'chargeType', 'ruleNameView'];
  const tableHeader = res.data.rows.map(item => {
    const obj = {};
    tableHeaderKeys.forEach(key => {
      obj[key] = item[key];
    });
    return obj;
  });
  const tableHeaderValues = ['计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上限(元)', '计费方式', '计费规则'];
  const workbook = utils.book_new();
  const worksheet = utils.json_to_sheet(tableHeader);
  utils.book_append_sheet(workbook, worksheet, 'Data');
  utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' });
  writeFileXLSX(workbook, 'test.xlsx');
};
// 计费规则的格式化
const formateType = (type) => {
  const Map = {
    duration: '时长计费',
    turn: '按次收费',
    partition: '分段计费'
  };
  return Map[type] || '';
};
// 打开弹框
const addFeeRules = () => {
  dialogVisible.value = true;

};
const showList = async (id) => {
    const res = await showRuleListAPI(id);
    console.log(res);
    
    Object.assign(addForm, res.data);
    editId.value = id;
  };
  
  const addFormRef =ref(null)
  const groupChange = (val) => {
    console.log(val);
  };
  const closeDialog = () => {
    dialogVisible.value = false
    addForm.chargeCeiling = null;
    addForm.freeDuration = null;
    editId.value = 0;
  };
  
  const addConfirm = async () => {
    const valid = await addFormRef.value.validate();
    if (!valid) return;
    if (editId.value === 0) { // 添加新的计费规则
      await addFeeRuleAPI(addForm);
      ElMessage.success('添加成功!');
    } else { // 编辑计费规则
      await editRuleListAPI(addForm);
      ElMessage.success('编辑成功!');
    }
    closeDialog(); // 关闭弹框
    getRuleList() // 页面刷新

  }
// 编辑计费规则
const editCarRule = (id) => {
  dialogVisible.value = true;
  console.log('addRuleRef',addRuleRef.value);
  showList(id)
};
// 删除计费规则
const deleteCarRule = async (id) => {
  ElMessageBox.alert('此操作将删除该计费规则, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteRuleListAPI(id);
    getRuleList();
    ElMessage.success('删除成功');
    if (ruleList.value.length === 1 && params.page > 1) {
      params.page--;
    }
    getRuleList()
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
  });
};
</script>


<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="addFeeRules">增加停车计费规则</el-button>
      <el-button @click="exportExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" :index="indexMethod" width="80" label="序号" />
        <el-table-column label="计费规则编号" prop="ruleNumber" min-width="120"/>
        <el-table-column label="计费规则名称" prop="ruleName" min-width="120"/>
        <el-table-column label="免费时长(分钟)" prop="freeDuration" min-width="120" />
        <el-table-column label="收费上限(元)" prop="chargeCeiling" min-width="120" />
        <el-table-column label="计费方式">
          <template #default="{ row }">
            {{ formateType(row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" min-width="200" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                <el-button type="primary" :icon="Edit" circle  @click="editCarRule(row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <el-button type="danger" :icon="Delete" circle  @click="deleteCarRule(row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页和eltable是相互独立的 -->
      <!-- 必须的配置项：total pagesize 总页数= 总页数/总容量 -->
      <div class="pager" style="margin-top: 20px">
        <el-pagination
          class="page-container"
          :total="total"
          :page-size="params.pageSize"
          layout="prev, pager, next"
          @current-change="editPageList"
        />
      </div>
    </div>
    <!-- 添加计费规则弹框 -->
     <!-- 弹框组件 -->
    <el-dialog
      width="680px"
      v-model="dialogVisible"
      :title="`${editId === 0 ? '添加计费规则' : '编辑计费规则'}`"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-position="top">
          <el-form-item label="计费规则编号" prop="ruleNumber">
            <el-input v-model="addForm.ruleNumber" />
          </el-form-item>
          <el-form-item label="计费规则名称" prop="ruleName">
            <el-input v-model="addForm.ruleName" />
          </el-form-item>
          <el-form-item label="计费方式" prop="chargeType">
            <el-radio-group v-model="addForm.chargeType" size="small" @change="groupChange">
              <el-radio value="duration" >时长收费</el-radio>
              <el-radio value="turn" >按次收费</el-radio>
              <el-radio value="partition" >分段收费</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="flex-container" style="display: flex; justify-content: space-between;">
            <el-form-item label="免费时长">
              <el-input v-model="addForm.freeDuration" style="width:150px" />
            </el-form-item>
            <el-form-item label="收费上限">
              <el-input v-model="addForm.chargeCeiling" style="width:150px" />
            </el-form-item>
          </div>
          <!-- 计费规则 -->
          <el-form-item label="计费规则" required>
            <!-- 时长计费区域 -->
            <div v-if="addForm.chargeType === 'duration'" class="duration" style="display: flex;">
              每
              <el-form-item prop="durationTime">
                <el-input v-model="addForm.durationTime" class="input-box" style="display: flex;" />
              </el-form-item>
              小时
              <el-form-item prop="durationPrice">
                <el-input v-model="addForm.durationPrice" class="input-box" style="width:150px" />
              </el-form-item>
              元
            </div>
            <!-- 按次收费区域 -->
            <div v-if="addForm.chargeType === 'turn'" class="turn" style="display:flex;">
              每次
              <el-form-item prop="turnPrice">
                <el-input v-model="addForm.turnPrice" class="input-box" style="width:150px" />
              </el-form-item>
              元
            </div>
            <!-- 分段计费区域 -->
            <div v-if="addForm.chargeType === 'partition'" class="partition">
              <div class="item" style="display: flex;">
                <el-form-item prop="partitionFrameTime">
                  <el-input v-model="addForm.partitionFrameTime" class="input-box" style="width:120px;" />
                </el-form-item>
                小时内，每小时收费
                <el-form-item prop="partitionFramePrice">
                  <el-input v-model="addForm.partitionFramePrice" class="input-box" style="width:120px;" />
                </el-form-item>
                元
              </div>
              <div class="item" style="display: flex; margin: 30px auto 0">
                <el-form-item prop="partitionIncreaseTime">
                  <el-input v-model="addForm.partitionIncreaseTime" class="input-box" style="width:120px;" />
                </el-form-item>
                小时超出后，增加
                <el-form-item prop="partitionIncreasePrice">
                  <el-input v-model="addForm.partitionIncreasePrice" class="input-box" style="width:120px;" />
                </el-form-item>
                元
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="addConfirm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<style lang="scss" scoped>
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
